package com.spsy.pay.controller.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: liuzhiping
 * @date: 2025/2/12 10:11
 **/
@RestController
@Slf4j
@RequestMapping("/mq")
public class RabbitmqController {

    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {


        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello 2206a4----------!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        Map<String,Object> map=new HashMap<>();

        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);

        //设置一个缓存的key
        this.redisTemplate.opsForValue().set(messageId,"1");



        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange2206a4", "TestDirectRouting2206a4", map);

        return "ok";
    }


    @GetMapping("/sendDirectMessage2")
    public void sendMessage() {


        System.out.println("====sendDirectMessage2 开始===");

        String payload =  "123456789";
        MessageProperties properties = new MessageProperties();

        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello 2206a!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);


        properties.setHeader("__TypeId__", payload.getClass().getName()); // 设置类型信息
        properties.setHeader("__ContentTypeId__","application/json");
        properties.setContentType("application/json");

        Message message = new Message(payload.toString().getBytes(), properties);

        System.out.println("====sendDirectMessage2 成功===");

        rabbitTemplate.convertAndSend("TestDirectExchange2206a", "TestDirectRouting2206a", message);
    }

}
